package top.as.sean.api.controller.common;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.common.collect.Maps;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.as.sean.common.id.SnowflakeId;
import top.as.sean.common.redis.RedisUtil;
import top.as.sean.common.response.Result;
import top.as.sean.dao.vo.system.CaptchaVo;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Map;

/**
 * 图形验证码
 *
 * @author: ArchieSean
 * @create: 2023/2/9
 */
@RestController
@RequestMapping("captcha")
@RequiredArgsConstructor
public class CaptchaController {

    private final DefaultKaptcha defaultKaptcha;

    private final HttpServletRequest request;

    /**
     * 获取图形验证码
     *
     * @return obj
     */
    @GetMapping("code")
    public Result<CaptchaVo> code() throws IOException {
        //生成文字验证码
        String text = defaultKaptcha.createText();

        request.getSession().setAttribute("code", text);
        // 生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", out);

        String idStr = SnowflakeId.createId().toString();
        //此处不用session，为了避免，多节点部署
        RedisUtil.set(idStr, text, 120L);
        CaptchaVo vo = CaptchaVo.builder().key(idStr).value(Base64.getEncoder().encodeToString(out.toByteArray())).build();
        out.close();
        return Result.success(vo);
    }
}
